package com.bo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bo.dto.CarHornDTO;
import com.bo.dto.ManufactureDTO;
import com.bo.dto.PrintDTO;
import com.bo.enity.*;
import com.bo.exception.RestUtil;
import com.bo.result.ParameterCodeEnum;
import com.bo.result.R;
import com.bo.result.Result;
import com.bo.result.ResultCodeEnum;
import com.bo.service.impl.*;
import com.bo.utils.HttpUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/print")
@Slf4j
public class PrintController {

    @RequestMapping("/result")
    public R getResult() {
        ResultCodeEnum resultCodeEnum = ResultCodeEnum.SUCCESS;
        return R.ok();
    }

    @RequestMapping("/exception")
    public R getException() {
        throw new NullPointerException();
    }

    // 静默打印服务路由地址
    public final static String printServiceUrl = "/api/printer/printing";

    /**
     * 打印服务
     *
     * @return
     */
    @ApiOperation(value = "打印服务", notes = "打印服务")
    @PostMapping(value = "/doPrint")    //中间件任务
    public R schedulingTask(@Validated @RequestBody PrintDTO params) throws SQLException {
        String clientIps = params.getClientIps();
        // 获取打印机IP地址
        String[] customerIps = clientIps.split(",");
        if(customerIps.length == 0) {
            log.error("未找到打印机IP地址");
            return R.error().message("未找到打印机IP地址");
        }
        //params对象转JSON字符串
        String jsonString = JSON.toJSONString(params);
        //请求打印服务
        for (String customerIp : customerIps) {
            String url = "http://" + customerIp + printServiceUrl;
            String res = HttpUtils.doPost(url, null, jsonString);
            log.info("[打印服务]静默打印请求结果：{}", res);
            //验证返回是否为JSON
            if(!HttpUtils.isValidJson(res)){
                log.error("[打印服务]返回数据不是JSON。");
                continue;
            }
            //验证返回结果
            JSONObject resObject = JSONObject.parseObject(res);
            String code = resObject.getString("Code");
            String msg = resObject.getString("Message");
            if (code == null || !code.equals("200")) {
                log.error("[打印服务]打印失败。原因：{}", msg);
                continue;
            }
            log.info("[打印服务]静默打印成功。");
        }

        return R.ok();
    }



}
